const express = require('express');
const { handleError, executeQuery, formatDateTime } = require('../utils');
const router = express.Router();

// 查询馆藏地列表
router.post('/list', async (req, res) => {
    const { page = 1, pageSize = 10, search = '' } = req.body;
    const offset = (page - 1) * pageSize;
    const limit = pageSize;

    const searchQuery = `%${search}%`;

    const totalQuery = `
        SELECT COUNT(*) AS total
        FROM librarylocation
        WHERE location_name LIKE ? OR address LIKE ?
    `;

    const query = `
        SELECT *
        FROM librarylocation
        WHERE location_name LIKE ? OR address LIKE ?
        LIMIT ${limit} OFFSET ${offset}
    `;

    try {
        const totalResult = await executeQuery(totalQuery, [searchQuery, searchQuery]);
        const total = totalResult[0].total;
        const locations = await executeQuery(query, [searchQuery, searchQuery]);

        locations.forEach(location => {
            location.created_at = formatDateTime(location.created_at);
            location.updated_at = formatDateTime(location.updated_at);
        });

        res.json({ total, page, pageSize, data: locations });
    } catch (error) {
        handleError(error, res);
    }
});

// 新增馆藏地
router.post('/add', async (req, res) => {
    const { location_name, address, description = null } = req.body;
    const query = `
        INSERT INTO librarylocation (location_name, address, description, created_at, updated_at)
        VALUES (?, ?, ?, NOW(), NOW());
    `;

    try {
        await executeQuery(query, [location_name, address, description]);
        res.json({ message: '馆藏地添加成功' });
    } catch (error) {
        handleError(error, res);
    }
});

// 更新馆藏地信息
router.post('/update', async (req, res) => {
    const { location_id, location_name, address, description = null } = req.body;
    const query = `
        UPDATE librarylocation
        SET location_name = ?, address = ?, description = ?, updated_at = NOW()
        WHERE location_id = ?;
    `;
    try {
        await executeQuery(query, [location_name, address, description, location_id]);
        res.json({ message: '馆藏地更新成功' });
    } catch (error) {
        handleError(error, res);
    }
});

// 删除馆藏地
router.post('/delete', async (req, res) => {
    const { location_id } = req.body;
    const query = 'DELETE FROM librarylocation WHERE location_id = ?';

    try {
        await executeQuery(query, [location_id]);
        res.json({ message: '馆藏地删除成功' });
    } catch (error) {
        if (error.code === 'ER_ROW_IS_REFERENCED_2') {
            res.status(400).json({ message: '该馆藏地已被引用，无法删除。请先删除相关借阅或委托记录。' });
        } else {
            handleError(error, res);
        }
    }
});

module.exports = router;
